package com.tanhua.dubbo.server.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.tanhua.common.exception.BusinessException;
import com.tanhua.common.mapper.UserInfoMapper;
import com.tanhua.common.pojo.Announcement;
import com.tanhua.common.pojo.User;
import com.tanhua.common.pojo.UserInfo;
import com.tanhua.common.utils.UserThreadLocal;
import com.tanhua.common.vo.ErrorResult;
import com.tanhua.dubbo.server.api.HuanXinApi;
import com.tanhua.dubbo.server.api.QuanZiApi;
import com.tanhua.dubbo.server.api.UsersApi;
import com.tanhua.dubbo.server.enums.CommentType;
import com.tanhua.dubbo.server.pojo.Comment;
import com.tanhua.dubbo.server.pojo.HuanXinUser;
import com.tanhua.dubbo.server.pojo.Users;
import com.tanhua.dubbo.server.vo.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 *
 * @ClassName: IMService
 * @Author:王晨晗
 * @Description:
 * @Date: 2022/01/05/19:17
 */
@Service
public class IMService {
    @Reference
    private HuanXinApi huanXinApi;
    @Autowired
    private UserInfoMapper userInfoMapper;
    @Reference
    private UsersApi usersApi;
    @Reference
    private QuanZiApi quanZiApi;
    @Autowired
    private AnnouncementService announcementService;

    /**
     * @description 根据环信用户名获取用户信息
     * @param userName
     * @return
     */
    public UserInfoVo queryUserInfoByUserName(String userName) {
        //查询环信用户
        HuanXinUser huanXinUser = huanXinApi.queryUserByUserName(userName);
       //判断是否为空,为空,表示该用户没有环信账户 , 返回null;
        if (ObjectUtil.isEmpty(huanXinUser)){
            return null;
        }

        //根据环信用户中对应的用户id 查询数据库,得到用户的详细信息
        QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id" , huanXinUser.getUserId());
        UserInfo userInfo = userInfoMapper.selectOne(wrapper);

        //判断用户是否存在
        if (ObjectUtil.isEmpty(userInfo)){
            return null;
        }

        //封装用户信息(婚姻需要特殊处理)
        UserInfoVo userInfoVo = BeanUtil.copyProperties(userInfo, UserInfoVo.class , "marriage");
        //userInfoVo.setGender(userInfo.getSex().toString().toLowerCase());
        userInfoVo.setGender(userInfo.getSex().getValue() == 1 ? "man" : "woman");
        userInfoVo.setMarriage(StrUtil.equals("已婚" , userInfo.getMarriage()) ? 1 : 0);

        //返回封装数据
        return userInfoVo;
    }

    /**
     * @description 添加好友
     * @param friendId
     * @return
     */
    public void contactUser(Long friendId) {
        //获取user
        User user = UserThreadLocal.get();

        //保存好友信息到数据库
        String id = usersApi.saveUsers(user.getId(), friendId);

        //判断是否保存成功
        if (StrUtil.isNotEmpty(id)){
            //注册好友关系到环信
            Boolean result = huanXinApi.addUserFriend(user.getId(), friendId);
            if (!result){
                throw new BusinessException(ErrorResult.huanxinContactsError());   //环信添加好友信息失败
            }
        }else{
            throw new BusinessException(ErrorResult.ContactsUserError()); // 数据库添加好友关系失败
        }
    }


    /**
     * @description 查询好友列表
     * @param page
     * @param pageSize
     * @param keyword
     * @return
     */
    public PageResult queryContactList(Integer page, Integer pageSize, String keyword) {
        //获取user
        User user = UserThreadLocal.get();
        //封装pageResult
        PageResult pageResult = new PageResult();
        pageResult.setPage(page);
        pageResult.setPagesize(pageSize);

        //获取好友列表
        List<Users> usersList;
        if (StrUtil.isEmpty(keyword)){
            usersList = usersApi.queryUsersList(user.getId(), page , pageSize);
        }else {
            usersList = usersApi.queryAllUsersList(user.getId());
        }

        //判断好友列表是否为空
        if (CollUtil.isEmpty(usersList)){
            return pageResult;
        }

        //查询数据库,获取好友详细信息
        //获取到所有的好友id
        List<Object> friendId = CollUtil.getFieldValues(usersList, "friendId");
        //查询用户信息表
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("user_id" , friendId);
        //判断是否需要模糊查询
        if (StringUtils.isNotEmpty(keyword)){
            queryWrapper.like("nick_name" , keyword);
        }

        List<UserInfo> userInfoList = userInfoMapper.selectList(queryWrapper);

        //填充用户信息
        List<UsersVo> contactList = new ArrayList<>();
        for (UserInfo userInfo : userInfoList) {
            UsersVo usersVo = new UsersVo();
            usersVo.setId(userInfo.getUserId());
            usersVo.setAge(userInfo.getAge());
            usersVo.setAvatar(userInfo.getLogo());
            usersVo.setGender(userInfo.getSex().name().toLowerCase());
            usersVo.setNickname(userInfo.getNickName());
            //环信用户账号
            usersVo.setUserId("HX_" + String.valueOf(userInfo.getUserId()));
            usersVo.setCity(StringUtils.substringBefore(userInfo.getCity(), "-"));
            contactList.add(usersVo);
        }

        pageResult.setItems(contactList);

        return pageResult;
    }

    /**
     * @description 查询消息点赞列表
     * @param page
     * @param pageSize
     * @return
     */
    public PageResult queryLikeCommentList(Integer page, Integer pageSize) {
        //获取用户信息
        User user = UserThreadLocal.get();
        //调用接口查询点赞列表信息
        List<Comment> commentList = quanZiApi.queryCommentListByUser(user.getId(), page, pageSize, CommentType.LIKE);
        //调用封装响应结果的方法,返回响应结果;
        return fillUserCommentList(commentList, page , pageSize);
    }

    /**
     * @description 查询消息喜欢列表
     * @param page
     * @param pageSize
     * @return
     */
    public PageResult queryLoveCommentList(Integer page, Integer pageSize) {
        //获取用户信息
        User user = UserThreadLocal.get();
        //调用接口查询喜欢列表信息
        List<Comment> commentList = quanZiApi.queryCommentListByUser(user.getId(), page, pageSize, CommentType.LOVE);
        //调用封装响应结果的方法,返回响应结果;
        return fillUserCommentList(commentList , page , pageSize);
    }

    /**
     * @description 查询消息评论列表
     * @param page
     * @param pageSize
     * @return
     */
    public PageResult queryUserCommentList(Integer page, Integer pageSize) {
        //获取用户信息
        User user = UserThreadLocal.get();
        //调用接口查询评论列表信息
        List<Comment> commentList = quanZiApi.queryCommentListByUser(user.getId(), page, pageSize, CommentType.COMMENT);
        //调用封装响应结果的方法,返回响应结果;
        return fillUserCommentList(commentList, page , pageSize);
    }

    /**
     * @description 封装我的消息列表的信息
     * @param commentList
     * @return
     */
    public PageResult fillUserCommentList(List<Comment> commentList,Integer page, Integer pageSize){
        //创建响应对象
        PageResult pageResult = new PageResult();
        //封装数据
        pageResult.setPage(page);  //当前页
        pageResult.setPagesize(pageSize); //每页条数
        //判断查询到的集合是否为空;
        if (CollUtil.isEmpty(commentList)){
            //没有查询到数据,返回封装结果;
              return pageResult;
        }
        //获取评论集合中的用户id;
        List<Object> userIds = CollUtil.getFieldValues(commentList, "userId");
        //查询用户详细表
        QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();
        wrapper.in("user_id" , userIds);
        List<UserInfo> userInfoList = userInfoMapper.selectList(wrapper);

        //封装响应数据实体集合
        List<MessageCommentVo> messageCommentVoList = new ArrayList<>();
        //遍历评论列表
        for (Comment comment : commentList) {
            //遍历用户信息集合
            for (UserInfo userInfo : userInfoList) {
                //判断两者对应关系
                if (ObjectUtil.equals(comment.getUserId() , userInfo.getUserId())){
                    //封装响应实体信息
                    MessageCommentVo messageCommentVo = new MessageCommentVo();
                    messageCommentVo.setId(comment.getId().toHexString());      //评论id
                    messageCommentVo.setAvatar(userInfo.getLogo());     //头像
                    messageCommentVo.setNickname(userInfo.getNickName()); //昵称
                    messageCommentVo.setCreateDate(DateUtil.format(new Date(comment.getCreated()) , "yyyy-MM-dd HH:mm"));  //评论时间

                    //添加到响应集合;
                    messageCommentVoList.add(messageCommentVo);
                    break;
                }
            }
        }
        //保存数据到pageResult
        pageResult.setItems(messageCommentVoList);
        //返回数据
        return pageResult;
    }


    /**
     * @description 查询公告列表
     * @param page
     * @param pageSize
     * @return
     */
    public PageResult queryMessageAnnouncementList(Integer page, Integer pageSize) {
        //获取查询出来的公告信息
        IPage<Announcement> announcementIPage = announcementService.queryList(page, pageSize);

        //封装响应数据
        List<AnnouncementVo> announcementVoList = new ArrayList<>();
        //遍历结果集
        for (Announcement record : announcementIPage.getRecords()) {
            AnnouncementVo announcementVo = new AnnouncementVo();
            announcementVo.setId(record.getId().toString());    //公告id
            announcementVo.setTitle(record.getTitle());     //公告标题
            announcementVo.setDescription(record.getDescription());  //公告描述
            announcementVo.setCreateDate(DateUtil.format(record.getCreated() , "yyyy-MM-dd HH:mm"));  //发布时间

            announcementVoList.add(announcementVo);
        }

        //封装pageResult
        PageResult pageResult = new PageResult();
        pageResult.setPage(page);
        pageResult.setPagesize(pageSize);
        pageResult.setItems(announcementVoList);

        return pageResult;
    }
}
